import { useMount, useRequest } from 'ahooks';
import { Spin } from 'antd';
import Card from 'antd/lib/card/Card';
import * as echarts from 'echarts';
import { useMemo, useRef, useEffect } from 'react';
import { useChartResize } from '@/utils/hooks';

const ChartItem = (props) => {
  const { getDataApi, createOption } = props
  const { data, loading } = useRequest(getDataApi)
  const option = useMemo(() => {
    if (!data) return null
    return (createOption(data))
  }, [data])
  const containerEl = useRef()
  const myChartins = useRef()
  useMount(() => {
    myChartins.current = echarts.init(containerEl.current);
    // 用ref存这个实例 一个函数中 用另一个实例
  })
  useEffect(() => {
    option && myChartins.current.setOption(option)
  }, [option])
  useChartResize(myChartins.current)
  return (
    <Spin spinning={loading}>
      <Card ref={containerEl} style={{ width: '100%', height: '300px' }} />
    </Spin>
  )
}
export default ChartItem
